package com.tidy.seed.admin.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tidy.seed.admin.system.service.RoleApiService;
import com.tidy.seed.admin.system.dto.AddApiIdsByRoleIdDTO;
import com.tidy.seed.admin.system.entity.RoleApi;
import com.tidy.seed.admin.system.mapper.RoleApiMapper;
import com.tidy.seed.admin.system.vo.UserApiPermissionVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author HZ-ZY
 * @since 2025-08-06
 */
@Service
public class RoleApiServiceImpl extends ServiceImpl<RoleApiMapper, RoleApi> implements RoleApiService {
    @Resource
    private RoleApiMapper roleApiMapper;

    @Override
    public Integer[] findApiIdsByRoleId(Integer roleId) {
        List<RoleApi> roleApiList = roleApiMapper.selectList(Wrappers.<RoleApi>query().eq("role_id", roleId));
        return roleApiList.stream()
                .map(RoleApi::getApiId)  // 假设RoleApi类有getApiId()方法获取接口ID
                .toArray(Integer[]::new);
    }

    @Override
    public Boolean addApiIdsByRoleId(AddApiIdsByRoleIdDTO dto) {
        //删除所有再新增
        roleApiMapper.delete(Wrappers.<RoleApi>query().eq("role_id", dto.getRoleId()));
        List<RoleApi> roleApiList = Arrays.stream(dto.getApiIds())
                .map(apiId -> {
                    RoleApi roleApi = new RoleApi();
                    roleApi.setRoleId(dto.getRoleId());
                    roleApi.setApiId(apiId);
                    return roleApi;
                })
                .collect(Collectors.toList());
        return this.saveBatch(roleApiList);
    }

    @Override
    public List<UserApiPermissionVO> getRoleIdsAndApisByUserId(Integer userId) {
        List<UserApiPermissionVO> userApiPermissionList = roleApiMapper.getRoleIdsAndApisByUserId(userId);
        //去重
        Map<Integer, UserApiPermissionVO> userApiPermissionMap = new LinkedHashMap<>();
        for (UserApiPermissionVO vo : userApiPermissionList) {
            userApiPermissionMap.putIfAbsent(vo.getApiId(), vo); //没有则插入
        }
        return new ArrayList<>(userApiPermissionMap.values());
    }
}
